package com.hunan.api.catv.service.biz.member.related;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.BindCardEnum;
import com.hunan.api.catv.entity.po.Member;
import com.hunan.api.catv.entity.po.MemberAccountRelated;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cps.CpsBiz;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.prize.PrizeBiz;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wangchao
 * @Date: 2021/4/8 9:16
 */
@Service
public class MemberAccountRelatedBiz extends ResultService {

    public static Logger log = LoggerFactory.getLogger(MemberAccountRelatedBiz.class);


    @Autowired
    CpsBiz cpsBiz;

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    PrizeBiz prizeBiz;

    /**
     * 大小屏账号绑定
     */
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult saveMemberAccountBind(MemberAccountRelated memberAccountRelated, Integer memberId, String version) {
        String userId = memberAccountRelated.getAccountId();
        String ca = memberAccountRelated.getCa();
        String mac = "";
        if (memberAccountRelated.getMac() != null) {
            mac = memberAccountRelated.getMac().indexOf("-") > 0 ? memberAccountRelated.getMac().replaceAll("-", ":") : memberAccountRelated.getMac();
        }
        /*if(StringUtils.isEmpty(userId)){
            return buildFail(ConstantsMsg.USER_ID_NOT_EMPTY);
        }*/
        Member member = new Member().selectById(memberId);
        if (member == null) {
            return buildFail(ConstantsMsg.member_simpleInfo_fail);
        }
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("smartCardCode", userId);
        map.put("resultType", BindCardEnum.INVALID.getCode());
        //获取该账号绑定的所有用户
        LambdaQueryWrapper<MemberAccountRelated> wrapper = new QueryWrapper<MemberAccountRelated>().lambda()
                .eq(MemberAccountRelated::getStatus, 1)
                .eq(MemberAccountRelated::getType, 2);
        if (StringUtils.isNoneBlank(userId)) {
            wrapper.eq(MemberAccountRelated::getAccountId, userId);
        } else if (StringUtils.isNoneBlank(ca)) {
            wrapper.eq(MemberAccountRelated::getCa, ca);
        } else {
            wrapper.eq(MemberAccountRelated::getMac, mac);
        }
        Integer count = new MemberAccountRelated().selectCount(wrapper);
        //获取目前已绑定用户
        if (count >= 10) {
            map.put("resultType", BindCardEnum.BEYOND.getCode());
            return buildFail(map, ConstantsMsg.cps_bind_beyond);
        }
        //判断该用户是否已绑定
        MemberAccountRelated memberAccountRelated2 = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().lambda()
                .eq(MemberAccountRelated::getMemberId, memberId)
                .eq(MemberAccountRelated::getType, 2));
        if (memberAccountRelated2 != null && memberAccountRelated2.getStatus() == 1) {
            map.put("resultType", BindCardEnum.BOUND.getCode());
            return buildFail(map, ConstantsMsg.cps_bind_already);
        }
        //校验大屏账号
        try {
            String smartCardCode = StringUtils.isEmpty(userId) ? (StringUtils.isEmpty(ca) ? mac : ca) : userId;
            ServiceResult serviceResult = cpsBiz.queryUserInfo(smartCardCode);
            if (!serviceResult.getStatus()) {
                return serviceResult;
            }
            MemberAccountRelated resultData = (MemberAccountRelated) serviceResult.getData();
            if (StringUtils.isNotBlank(userId) && !userId.equals(resultData.getAccountId())) {
                return buildFail(ConstantsMsg.USER_ID_INCONSISTENT);
            }
            //查询该用户是否绑定过
            boolean flag = false;
            Map<String, Object> popResult = null;
            if (memberAccountRelated2 != null && memberAccountRelated2.getStatus() == 0) {
                flag = memberAccountRelated2.setStatus(1).setTerminalType(resultData.getTerminalType()).setUpdateTime(new Date()).setAccountId(resultData.getAccountId()).setMac(resultData.getMac()).setCa(resultData.getCa()).setStbid(resultData.getStbid()).updateById();
                popResult = new HashMap<>();
                popResult.put("popFlag", false);
            } else {
                popResult = prizeBiz.getPrizeInfo(memberId, resultData.getAccountId(),version);
                flag = resultData.setMemberId(memberId).setCreateTime(new Date()).setUpdateTime(new Date()).setType(memberAccountRelated.getType()).insert();
            }
            log.info("维护大小屏绑定结果:{},data:{}", flag, resultData);
            if (flag) {
                member.setBindCa(1);
                member.setSmartCardCode(!StringUtils.isEmpty(resultData.getCa()) ? resultData.getCa() : resultData.getMac());
                boolean update = member.updateById();
                //添加绑定记录
                memberBiz.saveMemberBindRecord(1, memberId, StringUtils.isEmpty(resultData.getCa()) ? resultData.getMac() : resultData.getCa());
                log.info("修改用户绑定状态memberId:{},返回结果:{}", memberId, update);
                return buildOK(popResult, ConstantsMsg.cps_bind_success);
            }
        } catch (Exception e) {
            log.error("校验大屏账号失败userId:{},ca:{},mac:{},错误消息:{}", userId, ca, mac, e.getMessage());
        }
        return buildFail(map, ConstantsMsg.cps_bind_fail);
    }

    /**
     * 通过ca卡号或者mac地址获取hn账号
     */
    public String getAccountId(String smartCardCode) {
        QueryWrapper<MemberAccountRelated> wrapper = new QueryWrapper<>();
        if (smartCardCode.indexOf("-") > 0 || smartCardCode.indexOf(":") > 0) {
            wrapper.eq(MemberAccountRelated.MAC, smartCardCode);
        } else {
            wrapper.eq(MemberAccountRelated.CA, smartCardCode);
        }
        List<MemberAccountRelated> memberAccountRelatedList = new MemberAccountRelated().selectList(wrapper);
        if (!CollectionUtils.isEmpty(memberAccountRelatedList)) {
            smartCardCode = memberAccountRelatedList.get(0).getAccountId();
        }
        return smartCardCode;
    }

    public String getAccountByMemberId(Integer memberId) {
        MemberAccountRelated memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.MEMBER_ID, memberId).eq(MemberAccountRelated.STATUS, 1).eq(MemberAccountRelated.TYPE, 2).last("limit 1"));
        if (memberAccountRelated != null) {
            return memberAccountRelated.getAccountId();
        }
        return null;

    }
}
